const { connectDB, closeDB } = require('../mongoose/database');
const { initToClose } = require('../mongoose/database');
const BlogList = require('../data/blogListData');
// const Jwt = require('../data/jwtData')
const { verifyJwt, generateToken } = require('../utils/index')
const crypto = require('crypto');
const secret = crypto.randomBytes(20).toString('hex');
// 导出方法

const ava = [
  { url: 'http://localhost:51733/tx/tox1.png' },
  { url: 'http://localhost:51733/tx/tox2.png' },
  { url: 'http://localhost:51733/tx/tox3.png' },
  { url: 'http://localhost:51733/tx/tox4.png' },
  { url: 'http://localhost:51733/tx/tox5.png' },
]
const random = () => Math.floor(Math.random() * ava.length)
module.exports = {
  // async gets (req, res) {
  //   try {
  //     await connectDB();
  //     const blog = await BlogList.find();
  //     res.status(200).json(blog);
  //   } catch (error) {
  //     res.status(500).json({ message: error.message });
  //   }
  // }

  /* 
  业务逻辑
  1.获取用户token
  1.2如果用户token正确=>返回渲染数据
  1.3将页面渲染数据全部返回
  */
  async blogList (req, res) {
    let user = req.body
    console.log(req.headers.authorization, '211111')
    const is = await verifyJwt(req.headers.authorization)
    // if (!is) return res.status(401).json({ code: 401, msg: 'token失效' })
    initToClose(async () => {
      const data1 = await BlogList.find({})
      res.send({ code: 200, smg: '成功', data: data1 })
    })

  },
  // 查找 
  async blogOne (req, res) {
    let { id } = req.query
    let token = req.headers.authorization
    //用userId 查数据库 jwt的key  拿到key  2
    // const is = await verifyJwt(token)
    // is 是true 就通过
    // if (!is) return res.send({ code: 401, smg: '登陆过期' })
    initToClose(async () => {
      const blogitem = await BlogList.read(id)
      console.log(blogitem, '1111')
      res.send({ code: 200, data: blogitem })
    })
  },


  // 添加
  async blogAdd (req, res) {
    let { id, username, title, content, tags } = req.body
    console.log(id, username, title, content, tags)


    let token = req.headers.authorization
    //用userId 查数据库 jwt的key  拿到key  2
    const is = await verifyJwt(token)
    // is 是true 就通过
    if (!is) return res.send({ code: 401, smg: '登陆过期' })
    initToClose(async () => {
      const data = await BlogList.create({
        Avatar: ava[random()],
        comments: [],
        userId: is.id,
        tags: [tags],
        username: username,
        title: title,
        content: content,
        viewCount: 123,
      })
      if (!data) return res.send({ code: 200, msg: '添加失败' })
      res.send({ code: 200, msg: "成功", data: data })
    })
  },

  // 删除
  async blogdel (req, res) {
    let { id } = req.query; // 从请求体中获取id
    console.log(id, '要删除的ID');
    // 使用initToClose来确保数据库操作完成后关闭连接
    initToClose(async () => {
      try {
        const result = await BlogList.delete(id);
        if (!result) res.send({ code: 401, msg: '博客删除成失败', data: result });
        res.send({ code: 200, msg: '博客删除成功', data: result });
      } catch (err) {
        res.send({ msg: '数据库异常' })
      }
    });
  },

  // 编辑
  async bloged (req, res) {
    let { id, content, tags, title } = req.body
    const data = { content, tags, title, }
    initToClose(async () => {
      try {
        const result = await BlogList.update(id, data)
        if (result) res.send({ msg: '响应成功', data: result })
      } catch (err) {
        res.send({ code: 404, msg: '响应失败' })
      }
    })
    console.log(id, content, tags, title)
  },

  async blogcha (req, res) {

    let { title } = req.query
    console.log(title, '我查的是上面')
    initToClose(async () => {
      const data = await BlogList.find()
      // console.log(data)
      if(req.query === 'time'){
        
      }
      const news1 = data.filter(item => item.title.includes(title))
      if (news1.length < 1) res.send({ code: 401, msg: '没有这条数据哦' })
      res.send({ code: 200, msg: '成功', data: news1 })
    })

  },
}